package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-09-30
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;


    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否已经入住，入住已经入住，直接结束
        ElderCheckIn(checkInApplyDto);
        //2.更新床位为已入住(直接查到这个床位，后面会用)
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        //bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人信息
        Elder elder = InsterOrUpdateElder(checkInApplyDto.getCheckInElderDto(), bed);
        //4.新增入住办理
        saveContract(checkInApplyDto, elder);
        //5.新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder, bed);
        //6.新增入住配置
        SaveCheckInConfig(checkInApplyDto.getCheckInConfigDto(), checkIn.getId());
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //老人信息

        LambdaQueryWrapper<CheckIn> elqw = new LambdaQueryWrapper<>();
        elqw.eq(CheckIn::getId,id);
        CheckIn checkIn = checkInMapper.selectOne(elqw);

        Elder elder = elderMapper.selectElderById(checkIn.getElderId());

        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 老人家属信息
        String familyJson = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();

        if (StringUtils.isNotEmpty(familyJson)) {
            try {
                // 将 JSON 字符串转换为 ElderFamilyVo 列表
                elderFamilyVoList = JSON.parseArray(familyJson, ElderFamilyVo.class);
            } catch (Exception e) {
                // 处理 JSON 解析异常
               throw new BaseException("家属信息异常");
            }
        }

        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);


        //配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        LambdaQueryWrapper<CheckInConfig> cclaw = new LambdaQueryWrapper<>();
        cclaw.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(cclaw);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //合同信息
        LambdaQueryWrapper<Contract> clqw = new LambdaQueryWrapper<>();
        clqw.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(clqw);

        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInDetailVo.setContract(contract);



        return checkInDetailVo;
    }

    private void SaveCheckInConfig(CheckInConfigDto checkInConfigDto, Long id) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        //设置老人信息
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        //设置入住信息
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        //设置老人家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        String jsonString = JSON.toJSONString(elderFamilyDtoList);
        checkIn.setRemark(jsonString);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        //1.维护合同信息
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);

        //2.维护老人信息
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //3.如果当前时间比开始时间晚，则生效
        if (LocalDateTime.now().isAfter(contract.getStartDate())) {
                contract.setStatus(1);
        }
        //4.设置合同编号
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());

        contractMapper.insert(contract);
    }

    private void ElderCheckIn(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否已经入住，入住已经入住，直接结束
        LambdaQueryWrapper<Elder> elqw = new LambdaQueryWrapper<>();
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        elqw.eq(Elder::getIdCardNo, idCardNo)
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elqw);
        if (ObjectUtil.isNotNull(elder)) {
            //老人已经入住，直接结束，抛出异常——全局异常处理器来处理
            throw new BaseException("老人已入住");
        }
    }

    private Elder InsterOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        //3.新增或更新老人信息
        //3.1查询老人信息
        //3.1.1准备老人实体对象
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        //3.1.2设置床位信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //elderqw.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())

        Elder elderDb  = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));

        //3.2如果老人信息存在就跟新
        if (ObjectUtil.isNotNull(elderDb)) {
            elder.setId(elderDb.getId());
            elderMapper.updateElder(elder);
        } else {
            //3.3不存在则插入
            elderMapper.insert(elder);
        }
        return elder;
    }
}
